﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;
using System.IO;
using DoubleH.Utility;
using DoubleH.Utility.Configuration;
using System.Net;
using System.Net.Sockets;
using DoubleH.Utility.IO;
using Table=FCNS.Data.Table;
using System.Data;
using FSLib.IPMessager;
using System.Collections.ObjectModel;

namespace DHserver
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            InitVar();
            InitEvent();
        }

        IPMClient lanClient = null;
        ObservableCollection<StationStruct> allStation = new ObservableCollection<StationStruct>();

        private void InitVar()
        {
            dataGridExtStation.ItemsSource = allStation;
            foreach (IPAddress ip in Dns.GetHostAddresses(Dns.GetHostName()))
                comboBoxIp.Items.Add(ip.ToString());

            comboBoxIp.Text = DoubleHConfig.AppConfig.DefaultHost;

            StartNet();
            StartWeb();

            InitUI(false);
        }

        private void InitEvent()
        {
            comboBoxIp.SelectionChanged += (ss, ee) => ComboBoxIpSelectionChanged();
            this.Closing += (ss, ee) => CloseMe();
            buttonClear.Click += (ss, ee) => Clear();
            buttonJieZhuan.Click += (ss, ee) => JieZhuan();
            buttonLogin.Click += (ss, ee) => Login();
            buttonConfig.Click += (ss, ee) => ShowAppConfig();
        }

        private void ComboBoxIpSelectionChanged()
        {
            StopNet();
            DoubleHConfig.AppConfig.DefaultHost = comboBoxIp.SelectedItem.ToString();
            StartNet();
        }

        private void ShowAppConfig()
        {
            SysConfig.MainWindow mw = new SysConfig.MainWindow();
            mw.Init(null);
            mw.ShowDialog();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="bl">true 用户已登录,可以编辑控件内容.</param>
        private void InitUI(bool bl)
        {
            groupBox1.IsEnabled = bl;
            groupBox2.IsEnabled = bl;
            buttonClear.IsEnabled = bl;
            buttonLogin.IsEnabled = !bl;
            buttonConfig.IsEnabled = bl;
        }

        private void Login()
        {
            DoubleH.Utility.Login.LoginWindow lw = new DoubleH.Utility.Login.LoginWindow();
            lw.Init(Table.UserS.EnumFlag.操作员);
            lw.ShowDialog();
            if (Table.UserS.LoginUser == null || Table.UserS.LoginUser.UserNO != "root")
                return;

            InitUI(true);
            //结转
            if (FCNS.Data.DbDefine.JieZhuan.HasValue)
            {
                buttonJieZhuan.Content = "结转";
                labelJieZhuan.Content = FCNS.Data.DbDefine.JieZhuan.Value.ToShortDateString();
            }
        }

        private void JieZhuan()
        {
            bool ok = true;
            if (!buttonJieZhuan.Content.Equals("开账"))
            {
                switch (Table.SysConfig.SysConfigParams.JieZhuanMode)
                {
                    case 1:
                        if (DateTime.Now.Date < FCNS.Data.DbDefine.JieZhuan.Value.Date.AddMonths(1))
                        {
                            MessageWindow.Show("当前结转日期小于上次结转日期");
                            ok = false;
                        }
                        break;

                    case 2:
                        if (DateTime.Now.Date < FCNS.Data.DbDefine.JieZhuan.Value.AddDays(Table.SysConfig.SysConfigParams.JieZhuanRi))
                        {
                            MessageWindow.Show("当前结转日期小于上次结转日期");
                            ok = false;
                        }
                        break;

                    default:
                        {
                            MessageWindow.Show("系统未开启‘结转’功能");
                            ok = false;
                        }
                        break;
                }
            }
            if (ok)
            {
                Table.JieZhuanS js = new Table.JieZhuanS();
                js.OrderDateTime = DateTime.Now;
                Table.DataTableS.EnumDatabaseStatus result = js.Insert();
                if (result == Table.DataTableS.EnumDatabaseStatus.操作成功)
                {
                    buttonJieZhuan.Content = "结转";
                    labelJieZhuan.Content = FCNS.Data.DbDefine.JieZhuan.Value.ToShortDateString();
                }

                MessageWindow.Show(result.ToString());
            }
        }

        private void CloseMe()
        {
            DoubleHConfig.AppConfig.DefaultHost = comboBoxIp.Text;
            DoubleHConfig.AppConfig.DefaultHostPort = integerUpDownPort.Value.Value;

            ConfigSerializer.SaveConfig(DoubleHConfig.AppConfig, FCNS.Data.DbDefine.appConfigFile);

            StopNet();
            StopWeb();
        }

        private void Clear()
        {
            return; //需要登录数据库才可以清理
            //buttonClear.IsEnabled = false;
            //listBoxLog.Items.Insert(0, "开始清理 Data\\ProductS 目录");
            //List<string> ok = new List<string>();
            //foreach (DataRow row in SQLdata.GetDataRows("select UploadFile from ProductS"))
            //    ok.Add(row[0] as string);

            //foreach (string fi in Directory.GetFiles(DbDefine.dataDir + "ProductS"))
            //    if (!ok.Contains(System.IO.Path.GetFileName(fi)))
            //    {
            //        try { File.Delete(fi); }
            //        catch { listBoxLog.Items.Insert(0, fi + " 无法删除"); }
            //    }

            //buttonClear.IsEnabled = true;
        }

        //private void StartFileTransfer()
        //{
        //    //内网共享式访问
        //    //FileTools ft = new FileTools();
        //    //if (ft.ShareFolder(FCNS.Data.DbDefine.dataDir, "doubleH$", "use for DHserver"))
        //    //{
        //    //    loadFileServer = true;
        //    //    imageHost.Source = new BitmapImage(new Uri(@"Pack://application:,,,/DHserver;component/Images/right_24.png"));
        //    //}
        //    //else
        //    //    imageHost.Source = new BitmapImage(new Uri(@"Pack://application:,,,/DHserver;component/Images/error_24.png"));
        //    //远程访问
        //    //SocketServerManager.Init(DoubleHConfig.AppConfig.Server);
        //    //SocketServerManager.Start();
        //}


        //static Config.ClientConfig GetDefaultConfig()
        //{
        //    return new ClientConfig()
        //    {
        //        IPMClientConfig = new FSLib.IPMessager.Entity.Config
        //        {
        //            Port = 2425,
        //            GroupName = Environment.MachineName,
        //            NickName = Environment.UserName,
        //            ForceOldContract = true,
        //            IgnoreNoAddListFlag = false,
        //            EnableHostNotifyBroadcast = false,
        //            HostName = Environment.MachineName,
        //            AutoReplyWhenAbsence = true,
        //            AutoDetectVersion = true,
        //            BanedHost = new List<string>(),
        //            KeepedHostList = new List<string>(),
        //            BindedIP = IPAddress.Any,
        //            VersionInfo = "程序版本号: " ,
        //            AbsenceSuffix = " [离开]",
        //            Services = ServiceManager.GetServices(new string[] { "addins" }),
        //            EnableBPContinue = true,
        //            TaskKeepTime = 600,
        //            TasksMultiReceiveCount = 1
        //        },
        //        AbsenceMessage = new List<string>()
        //        {
        //            "我有事暂时不在，稍后联系你",
        //            "我吃饭去了！",
        //            "有事启奏 >_< 无事退朝",
        //            "还钱请电话，借钱请关机！"
        //        },

        //        HostGroupConfig = new SerializableDictionary<string, string>(),
        //    };
        //}

        //#region file transfer
        //private void StartFileTransfer()
        //{
        //    if (string.IsNullOrEmpty(comboBoxIp.Text))
        //        return;

        //    loadFileServer = true;
        //    imageHost.Source = new BitmapImage(new Uri(@"Pack://application:,,,/DHserver;component/Images/right_24.png"));


        //    //Control.CheckForIllegalCrossThreadCalls = false;
        //    D_ThreadRec _D_ThreadRec = new D_ThreadRec(ThreadRec);
        //    _D_ThreadRec.BeginInvoke(null, null);
        //}

        //private void StopFileTransfer()
        //{
        //    loadFileServer = false;
        //    if (serverSocket != null)
        //        serverSocket.Close();

        //    imageHost.Source = new BitmapImage(new Uri(@"Pack://application:,,,/DHserver;component/Images/error_24.png"));
        //}

        ///// <summary>
        ///// 监听服务函数
        ///// </summary>
        //private void ThreadRec()
        //{
        //    try
        //    {
        //        IPAddress ip = IPAddress.Parse(DoubleHConfig.AppConfig.DefaultHost);
        //        IPEndPoint ipe = new IPEndPoint(ip, DoubleHConfig.AppConfig.DefaultHostPort);
        //        serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        //        serverSocket.Bind(ipe);
        //        serverSocket.Listen(10);
        //        ErrorS.WriteLogFile("服务器开始监听" + DoubleHConfig.AppConfig.DefaultHostPort + "端口！");
        //        while (true)
        //        {
        //            if (loadFileServer == true)
        //            {
        //                try
        //                {
        //                    //阻塞监听至到有新的连接
        //                    Socket temp = serverSocket.Accept();
        //                    IPEndPoint clientip = (IPEndPoint)temp.RemoteEndPoint;
        //                    //如果连接上
        //                    if (temp.Connected)
        //                    {
        //                        ServerReceiveFile startThreads = new ServerReceiveFile(temp);
        //                    }
        //                }
        //                catch (Exception ex)
        //                {
        //                    if (ex.Message != "一个封锁操作被对 WSACancelBlockingCall 的调用中断。")//断开socket时阻塞监听的报错提示
        //                        MessageBox.Show(ex.Message);
        //                }
        //            }
        //            else
        //            {

        //                serverSocket.Close();
        //                ErrorS.WriteLogFile("停止监听服务！");
        //                break;
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageWindow.Show(ex.Message);
        //        ErrorS.WriteLogFile(ex.Message);
        //    }
        //}
        //#endregion
    }
}